package cn.itcast.demo;

import cn.itcast.EsApplication;
import cn.itcast.demo.pojo.Item;
import cn.itcast.demo.repository.ItemRepository;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = EsApplication.class)
public class SelfQueryDemo {
    @Autowired
    private ItemRepository itemRepository;

    @Test
    public void testQueryTitle(){
        //定义一个查询条件的构建工具
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        //给构建工具中添加查询条件
        queryBuilder.withQuery(QueryBuilders.matchQuery("title","小米").operator(Operator.AND));

        //执行查询，把查询条件的构建工具中的查询条件进行build构造，创建成查询条件对象
        Page<Item> itemPage = itemRepository.search(queryBuilder.build());

        List<Item> content = itemPage.getContent();

        content.forEach(ct->{
            System.out.println("ct = " + ct.getId()+","+ct.getTitle());
        });


    }
    @Test
    public void testSortQueryTitle(){
        //定义一个查询条件的构建工具
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        //给构建工具中添加查询条件
        queryBuilder.withQuery(QueryBuilders.matchQuery("title","小米").operator(Operator.AND));

        queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));

        //执行查询，把查询条件的构建工具中的查询条件进行build构造，创建成查询条件对象
        Page<Item> itemPage = itemRepository.search(queryBuilder.build());

        List<Item> content = itemPage.getContent();

        content.forEach(ct->{
            System.out.println(ct);
        });

    }
    @Test
    public void testPageQueryTitle(){
        //定义一个查询条件的构建工具
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        //给构建工具中添加查询条件
        queryBuilder.withQuery(QueryBuilders.matchQuery("category","手机").operator(Operator.AND));

        //设置分页条件，第一个参数page表示页码，第二个参数表示页容量
        //在springData中分页从0开始计数页码，今后使用页码会以变量的形式传入，一定要记得在这里-1
        queryBuilder.withPageable(PageRequest.of(2,2));


        //执行查询，把查询条件的构建工具中的查询条件进行build构造，创建成查询条件对象
        Page<Item> itemPage = itemRepository.search(queryBuilder.build());

        List<Item> content = itemPage.getContent();

        content.forEach(ct->{
            System.out.println(ct);
        });

    }

}
